<template>
  <div>
    <!--引用表格-->
   <BasicTable @register="registerTable" :rowSelection="rowSelection">
     <!--插槽:table标题-->
      <template #tableTitle>
          <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
          <a-button  type="primary" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
          <!-- <j-upload-button  type="primary" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button> -->
          <a-dropdown v-if="selectedRowKeys.length > 0">
              <template #overlay>
                <a-menu>
           <!--       <a-menu-item key="1" @click="batchHandleDelete">
                    <Icon icon="ant-design:delete-outlined"></Icon>
                    删除
                  </a-menu-item>-->
                </a-menu>
              </template>
             <!-- <a-button>批量操作
                <Icon icon="mdi:chevron-down"></Icon>
              </a-button>-->
        </a-dropdown>
      </template>
       <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)"/>
      </template>
      <!--字段回显插槽-->
      <template v-slot:bodyCell="{ column, record, index, text }">
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <MonsterRocProjectSetupModal @register="registerModal" @success="handleSuccess"></MonsterRocProjectSetupModal>
  </div>
</template>

<script lang="ts" name="monster-monsterRocProjectSetup" setup>
  import dayjs from 'dayjs'
  import {BasicTable, useTable, TableAction} from '/@/components/Table';
  // import rocWordPage from './components/rocWordPage.vue'
  import {useModal} from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage'
  import MonsterRocProjectSetupModal from './components/MonsterRocProjectSetupModal.vue'
  import {columns, searchFormSchema} from './MonsterRocProjectSetup.data';
  import {
    list,
    deleteOne,
    batchDelete,
    getImportUrl,
    getExportUrl,
    getRcConfig,
    sendProjectSetupApply,
    closeProject
  } from './MonsterRocProjectSetup.api';
  import { downloadFile } from '/@/utils/common/renderUtils';
  import { useUserStore } from '/@/store/modules/user';
  import { USER_INFO_KEY } from '/@/enums/cacheEnum'
  import { getAuthCache } from '/@/utils/auth'
  let user = getAuthCache(USER_INFO_KEY) || {}
  //注册model
  const [registerModal, {openModal}] = useModal();
  //注册table数据
  const { prefixCls,tableContext,onExportXls,onImportXls } = useListPage({
      tableProps:{
           title: 'monster_roc_project_setup',
           api: list,
           columns,
           canResize:false,
          /* beforeFetch: (t) => {
            return Object.assign(t,{createBy: user.createBy})
           },*/
           formConfig: {
              //labelWidth: 120,
              schemas: searchFormSchema,
              autoSubmitOnEnter:true,
              showAdvancedButton:true,
              fieldMapToNumber: [
              ],
              fieldMapToTime: [
              ],
            },
           actionColumn: {
               width: 200,
               fixed:'right'
            },
      },
      exportConfig: {
        name:"monster_roc_project_setup",
        url: getExportUrl,
      },
      importConfig: {
        url: getImportUrl,
        success: handleSuccess
      },
  })

  const [registerTable, {reload},{ rowSelection, selectedRowKeys }] = tableContext

   /**
    * 新增事件
    */
  function handleAdd() {
    getRcConfig().then((res) => {
      let record = {
        operationPercent: res.operationPercent,
        kpi: res.kpi,
        faxPercent: res.fax,
        createBy: user.username,
        setupStatus: 1
      }
      openModal(true, {
        record,
        isUpdate: false,
        showFooter: true,
      })
    })
  }
   /**
    * 编辑事件
    */
  function handleEdit(record: Recordable) {
      // 处理图片
      let img:any = []
      let file = record.annexList ? JSON.parse(JSON.stringify(record.annexList)) : []
      file.forEach((item) => {
        img.push({
          uid: item.id,
          fileName: item.annexName,
          filePath: item.url,
          status: 'done',
          response: {
            status: 'history',
            message: item.url
          }
        })
      })
      openModal(true, {
       record: Object.assign(record,{uploadFile:JSON.stringify(img)}),
      // record,
       isUpdate: true,
       showFooter: true,
      });
   }

  function handleApply(record: Recordable) {
    let p = {
      projectId: record.id,
      projectName: record.projectName,
      applyProjectType: 1, // ROC类的就传1
      applyStatus: 3,
      applyer: user.id,
      applyContent: 'RC立项送审',
      sendApplyTime: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
    }
    sendProjectSetupApply(p).then((res) => {
      handleSuccess()
    })
  }

  function handleClose(record) {
    console.log('record',record)
    let q = {
      id: record.id
    }
    closeProject(q).then((res) => {
      handleSuccess()
    })
  }

   /**
    * 详情
   */
  function handleDetail(record: Recordable) {
     // 处理图片
      let img:any = []
      let file = record.annexList ? JSON.parse(JSON.stringify(record.annexList)) : []
      file.forEach((item) => {
        img.push({
          uid: item.id,
          fileName: item.annexName,
          filePath: item.url,
          status: 'done',
          response: {
            status: 'history',
            message: item.url
          }
        })
      })
     openModal(true, {
        record: Object.assign(record,{uploadFile:JSON.stringify(img)}),
       isUpdate: true,
       showFooter: false,
     });
   }
   /**
    * 删除事件
    */
  async function handleDelete(record) {
     await deleteOne({id: record.id}, handleSuccess);
   }
   /**
    * 批量删除事件
    */
  async function batchHandleDelete() {
     await batchDelete({ids: selectedRowKeys.value}, handleSuccess);
   }
   /**
    * 成功回调
    */
  function handleSuccess() {
      (selectedRowKeys.value = []) && reload();
   }
   /**
      * 操作栏
      * 送审中  不显示编辑 不显示 送审
      立项通过  不显示送审  显示编辑
   */
  function getTableAction(record){
    let def = [
      {
        label: '详情',
        onClick: handleDetail.bind(null, record),
      }
/*      ,
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
          placement: 'topLeft',
        }
      }*/
    ]
    let sendApply = [{
      label: '送审',
      popConfirm: {
        title: '是否确认送审',
        confirm: handleApply.bind(null, record),
        placement: 'topLeft',
      }
    }]

     let edit = [
       {
         label: '编辑',
         onClick: handleEdit.bind(null, record)
       }]

     let close = [
       {
         label: '关闭',
         popConfirm: {
           title: '是否确认关闭',
           confirm: handleClose.bind(null,record),
           placement: 'topLeft',
         }
       }
     ]
     //1 立项草拟  2 立项送审 3 立项审批通过  4 立项审批拒绝
     //项目状态  0 立项中 1 进行中 2 已关闭 3 已结束
     if((record.setupStatus == 1 ||record.setupStatus == 4 ) && record.projectStatus == 0 ) {
         return [...sendApply,...edit,...def,...close]
     }
     if(record.setupStatus == 3 && record.projectStatus == 1 ) {
       return [...def,...close]
     }
     else {
      return def
    }
  }
    /**
    * 下拉操作栏
    */
  function getDropDownAction(record){
    let arr  = [
      {
        label: '详情',
        onClick: handleDetail.bind(null, record),
      }

 /*     , {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
          placement: 'topLeft',
        }
      }*/
    ]
      // == 3
    if(record.setupStatus == 1 || record.setupStatus == 4) {
      arr.unshift({
        label: '编辑',
        onClick: handleEdit.bind(null, record)
      })
    }
    return []//arr
  }

</script>

<style scoped>

</style>
